package org.jeecg.modules.paycenter.channel.bankdocking.utils;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;

import javax.servlet.http.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * @description: 批量下载文件
 * @author: Wzq
 * @create: 2019-11-25 10:17
 */
@Slf4j
public class BatchDownFilesUtils {

    /**
     *@Description 输入文件集合，zipPath临时路径,request,response导出zip文件
     *@Param [files, zipPath, request, response]
     *@Return javax.servlet.http.HttpServletResponse
     *@Author Wzq
     *@Date 2019/11/25
     *@Time 19:49
     */
    public static HttpServletResponse downLoadFiles(List<File> files, String zipPath, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            /**这个集合就是你想要打包的所有文件，
             * 这里假设已经准备好了所要打包的文件
             */

            //List<File> files = new ArrayList<File>();

            /**创建一个临时压缩文件，
             * 我们会把文件流全部注入到这个文件中
             * 这里的文件你可以自定义是.rar还是.zip
             　　      * 这里的file路径发布到生产环境时可以改为
             */
            File file = new File(zipPath);
            if (!file.exists()){
                file.createNewFile();
            }
            response.reset();
            //response.getWriter()
            //创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);
            /**打包的方法我们会用到ZipOutputStream这样一个输出流,
             * 所以这里我们把输出流转换一下*/
            //org.apache.tools.zip.ZipOutputStream zipOut = new org.apache.tools.zip.ZipOutputStream(fous);
            ZipOutputStream zipOut = new ZipOutputStream(fous);
            /**这个方法接受的就是一个所要打包文件的集合，
             * 还有一个ZipOutputStream
             */
            zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return downloadZip(file,response);
        }catch (Exception e) {
            e.printStackTrace();
        }
        /**直到文件的打包已经成功了，
         * 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中，
         * 稍后会呈现出来，接下来的就是往客户端写数据了
         */
        // OutputStream out = response.getOutputStream();


        return response ;
    }

    /**
     * 把接受的全部文件打成压缩包
     * @param List<File>;
     * @param org.apache.tools.zip.ZipOutputStream
     */
    private static void zipFile(List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }

    /**
     *@Description 下载zip文件，删除缓存文件
     *@Param [file, response]
     *@Return javax.servlet.http.HttpServletResponse
     *@Author Wzq
     *@Date 2019/11/25
     *@Time 19:48
     */
    private static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            try {
                File f = new File(file.getPath());
                f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 根据输入的文件与输出流对文件进行打包
     * @param File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    private static void zipFile(File inputFile, ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                /**如果是目录的话这里是不采取操作的，
                 * 至于目录的打包正在研究中
                 */
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 选择保存路径
     * @return
     */
    public static File selectDir(){
        JFileChooser jfc = new JFileChooser();
        //后缀名过滤器
        FileNameExtensionFilter filter = new FileNameExtensionFilter("(*.zip)","zip");
        jfc.setFileFilter(filter);

        //设置当前路径为桌面路径,否则将我的文档作为默认路径
        FileSystemView fsv = FileSystemView.getFileSystemView();
        jfc.setCurrentDirectory(fsv.getHomeDirectory());
        //设置只选择路径
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //弹出的提示框的标题
        jfc.showDialog(new JLabel(), "保存");
//        int option = jfc.showSaveDialog(null);
//        if(option == JFileChooser.APPROVE_OPTION) {    //假如用户选择了保存
            //用户选择的路径或文件
            File file = jfc.getSelectedFile();
            return file;
//        }else{
//            return null;
//        }
    }
    /**
     * 获取桌面路径
     * @return
     */
    public static File getDesktopDir(){
        //设置当前路径为桌面路径,否则将我的文档作为默认路径
        FileSystemView fsv = FileSystemView.getFileSystemView();
        return fsv.getHomeDirectory();
    }

    /**
     * 把文件集合打成zip压缩包
     * @param srcFiles 压缩文件集合
     * @param zipFile  zip文件名
     * @throws RuntimeException 异常
     */
    public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
//        long start = System.currentTimeMillis();
        if(zipFile == null){
            log.error("压缩包文件名为空！");
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
            log.error("压缩包文件名异常，zipFile={}", zipFile.getPath());
            return;
        }
        ZipOutputStream zos = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.setComment("注释");
                zos.closeEntry();
                in.close();
            }
//            long end = System.currentTimeMillis();
//            log.info("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            log.error("BatchDownFilesUtils toZip exception, ", e);
            throw new RuntimeException("zipFile error from BatchDownFilesUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    log.error("BatchDownFilesUtils toZip zos close exception, ", e);
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("BatchDownFilesUtils toZip out close exception, ", e);
                }
            }
        }
    }

    public static void main(String[] args) {
        File zipPath = selectDir();
        if (zipPath != null) {
            List<File> srcFiles = new ArrayList<>();
            srcFiles.add(new File("C:\\opt\\bank\\CMRA76.15491101040043467_20210520_259850201_15302598502015193702.pdf"));
            srcFiles.add(new File("C:\\opt\\bank\\CMRA76.15491101040043467_20210520_259882376_15302598823768289990.pdf"));
            srcFiles.add(new File("C:\\opt\\bank\\CMRA76.15491101040043467_20210618_521530880_15305215308800080921.pdf"));
            File zipFile = new File(zipPath + File.separator + "银行电子回单_" + DateUtils.getDate("yyyyMMddHHmmss") + ".zip");
            toZip(srcFiles, zipFile);
        }
//        System.out.println(selectDir());
    }
}


